package com.innovation.ic.im.end.web.controller.im_erp9;

import com.innovation.ic.b1b.framework.util.StringUtils;
import com.innovation.ic.im.end.base.pojo.ApiResult;
import com.innovation.ic.im.end.base.pojo.ServiceResult;
import com.innovation.ic.im.end.base.pojo.constant.Constants;
import com.innovation.ic.im.end.base.pojo.constant.RedisStorage;
import com.innovation.ic.im.end.base.pojo.im_erp9.GroupPojo;
import com.innovation.ic.im.end.base.thread.data.InsertUserCurrentDataToRedisThread;
import com.innovation.ic.im.end.web.controller.AbstractController;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 群组和账号的关系API
 */
@Api(value = "群组和账号的关系API", tags = "RefGroupAccountController")
@RestController
@RequestMapping("/api/v1/refGroupAccount")
@DefaultProperties(defaultFallback = "defaultFallback")
public class RefGroupAccountController extends AbstractController {
    private static final Logger log = LoggerFactory.getLogger(RefGroupAccountController.class);

    /**
     * 设置某个用户对某个群组消息免打扰
     * @return
     */
    @HystrixCommand
    @ApiOperation(value = "设置某个用户对某个群组消息免打扰")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "groupId", value = "群组id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "accountId", value = "账号id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "username", value = "账号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "status", value = "状态。1表示设置为消息免打扰。0表示取消消息免打扰", required = true, dataType = "Integer")
    })
    @RequestMapping(value = "/noReminder/{groupId}/{accountId}/{username}/{status}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> noReminder(@PathVariable("groupId") String groupId,
                                                         @PathVariable("accountId") String accountId,
                                                         @PathVariable("username") String username,
                                                         @PathVariable("status") Integer status,
                                                         HttpServletRequest request, HttpServletResponse response) {
        if (!StringUtils.validateParameter(groupId) || !StringUtils.validateParameter(accountId)
                || !StringUtils.validateParameter(username) || null == status) {
            String message = "调用接口【/api/v1/refGroupAccount/noReminder/{groupId}/{accountId}/{username}/{status}时，参数groupId、accountId、username和status不能为空";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        ServiceResult<Boolean> result = refGroupAccountService.updateRefGroupAccountStatus(groupId, accountId, username, status);
        if(result.getResult()){
            // 将用户最近联系人的信息导入redis
            List<String> userNameList = new ArrayList<>();
            userNameList.add(username);
            InsertUserCurrentDataToRedisThread insertUserCurrentDataToRedisThread = new InsertUserCurrentDataToRedisThread(userNameList, redisManager, userGroupService, Boolean.TRUE, rabbitMqParamConfig);
            threadPoolManager.execute(insertUserCurrentDataToRedisThread);
        }

        ApiResult<Boolean> apiResult = new ApiResult<>();
        apiResult.setSuccess(result.getSuccess());
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(result.getMessage());
        apiResult.setResult(result.getResult());
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 将某个用户对某个群组设置为置顶
     * @return
     */
    @HystrixCommand
    @ApiOperation(value = "将某个用户对某个群组设置为置顶")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "groupId", value = "群组id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "accountId", value = "账号id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "username", value = "账号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "status", value = "状态。1表示设置为置顶。0表示取消置顶", required = true, dataType = "Integer")
    })
    @RequestMapping(value = "/topping/{groupId}/{accountId}/{username}/{status}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> topping(@PathVariable("groupId") String groupId,
                                                      @PathVariable("accountId") String accountId,
                                                      @PathVariable("username") String username,
                                                      @PathVariable("status") Integer status,
                                                      HttpServletRequest request, HttpServletResponse response) throws ParseException {
        if (!StringUtils.validateParameter(groupId) || !StringUtils.validateParameter(accountId)
                || !StringUtils.validateParameter(username) || null == status) {
            String message = "调用接口【/api/v1/refGroupAccount/topping/{groupId}/{accountId}/{username}/{status}时，参数groupId、accountId、username和status不能为空";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        ServiceResult<Boolean> result = refGroupAccountService.updateRefGroupAccount(groupId, accountId, username, status);
        if(result.getResult()){
            // 将用户最近联系人的信息导入redis
            List<String> userNameList = new ArrayList<>();
            userNameList.add(username);
            InsertUserCurrentDataToRedisThread insertUserCurrentDataToRedisThread = new InsertUserCurrentDataToRedisThread(userNameList, redisManager, userGroupService, Boolean.TRUE, rabbitMqParamConfig);
            threadPoolManager.execute(insertUserCurrentDataToRedisThread);
        }

        ApiResult<Boolean> apiResult = new ApiResult<>();
        apiResult.setSuccess(result.getSuccess());
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(result.getMessage());
        apiResult.setResult(result.getResult());
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 返回某个默认群组的详细信息，包括：主键，群组id，群组名称，是否消息免打扰，置顶时间，成员列表
     * @return
     */
    @HystrixCommand
    @ApiOperation(value = "返回某个默认群组的详细信息，包括：主键，群组id，群组名称，是否消息免打扰，置顶时间，成员列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "groupId", value = "群组id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "accountId", value = "账号id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "username", value = "账号", required = true, dataType = "String")
    })
    @RequestMapping(value = "/detail/{groupId}/{accountId}/{username}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> detail(@PathVariable("groupId") String groupId,
                                                       @PathVariable("accountId") String accountId,
                                                       @PathVariable("username") String username,
                                                       HttpServletRequest request, HttpServletResponse response) throws ParseException {
        if (StringUtils.isEmpty(groupId) || StringUtils.isEmpty(accountId)
                || StringUtils.isEmpty(username)) {
            String message = "调用接口【/api/v1/refGroupAccount/detail/{groupId}/{accountId}/{username}时，参数groupId、accountId、username不能为空";
            log.warn(message);
            ApiResult<GroupPojo> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        // 查询默认群组信息
        Map<String, Object> map = new HashMap<String, Object>();
        map.put(Constants.GROUP_ID, groupId);
        map.put(Constants.ACCOUNT_ID, accountId);
        map.put(Constants.USER_NAME, username);
        ServiceResult<GroupPojo> result = refGroupAccountService.getGroupDetailInfoByParam(map);

        ApiResult<GroupPojo> apiResult = new ApiResult<>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(ServiceResult.SELECT_SUCCESS);
        apiResult.setResult(result.getResult());
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 用户username在组groupId中某个时间之前的聊天记录，对username不可见
     * @return
     */
    @HystrixCommand
    @ApiOperation(value = "用户username在组groupId中某个时间之前的聊天记录，对username不可见")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "groupId", value = "默认群组账号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "accountId", value = "用户账号id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "username", value = "用户账号", required = true, dataType = "String")
    })
    @RequestMapping(value = "/invisible/{groupId}/{accountId}/{username}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> invisible(@PathVariable("groupId") String groupId,
                                                        @PathVariable("accountId") String accountId,
                                                        @PathVariable("username") String username,
                                                        HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(groupId) || StringUtils.isEmpty(accountId)
            || StringUtils.isEmpty(username)) {
            String message = "调用接口【/api/v1/refGroupAccount/invisible/{groupId}/{accountId}/{username}时，参数groupId、accountId、username不能为空";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        // 根据用户设置默认群组聊天内容不可见时间
        Map<String, Object> map = new HashMap<>();
        map.put(Constants.GROUP_ID, groupId);
        map.put(Constants.ACCOUNT_ID, accountId);
        map.put(Constants.USER_NAME, username);
        ServiceResult<Boolean> result = refGroupAccountService.invisibleChatRecordSet(map);

        ApiResult<Boolean> apiResult = new ApiResult<>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        apiResult.setResult(result.getResult());
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 将默认群组groupId从用户username的最近联系人中删除，并且清除当前时间之前用户username可看到的群聊天记录
     * @return 返回删除结果
     */
    @HystrixCommand
    @ApiOperation(value = "将默认群组groupId从用户username的最近联系人中删除，并且清除当前时间之前用户username可看到的群聊天记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "groupId", value = "默认群组账号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "accountId", value = "用户账号id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "username", value = "用户账号", required = true, dataType = "String")
    })
    @RequestMapping(value = "/deleteGroupChat/{groupId}/{accountId}/{username}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> deleteGroupChat(@PathVariable("groupId") String groupId,
                                               @PathVariable("accountId") String accountId,
                                               @PathVariable("username") String username,
                                               HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(groupId) || StringUtils.isEmpty(accountId)
                || StringUtils.isEmpty(username)) {
            String message = "调用接口【/api/v1/refGroupAccount/deleteGroupChat/{groupId}/{accountId}/{username}时，参数groupId、accountId、username不能为空";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        // 删除最近联系群组并清除聊天记录
        Map<String, Object> map = new HashMap<>();
        map.put(Constants.GROUP_ID, groupId);
        map.put(Constants.ACCOUNT_ID, accountId);
        map.put(Constants.USER_NAME, username);
        ServiceResult<Boolean> result = refGroupAccountService.deleteGroupChat(map);
        if(result.getResult()){
            // 将用户最近联系人的信息导入redis
            List<String> userNameList = new ArrayList<>();
            userNameList.add(username);
            InsertUserCurrentDataToRedisThread insertUserCurrentDataToRedisThread = new InsertUserCurrentDataToRedisThread(userNameList, redisManager, userGroupService, Boolean.TRUE, rabbitMqParamConfig);
            threadPoolManager.execute(insertUserCurrentDataToRedisThread);
        }

        ApiResult<Boolean> apiResult = new ApiResult<>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        apiResult.setResult(result.getResult());
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 根据群组Id获取默认群组中的人数
     * @param groupId
     * @param request
     * @param response
     * @return
     */
    @HystrixCommand
    @ApiOperation(value = "根据群组Id获取默认群组中的人数")
    @ApiImplicitParam(name = "groupId", value = "群组id", required = true, dataType = "String")
    @RequestMapping(value = "/count/{groupId}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> count(@PathVariable("groupId") String groupId, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(groupId)) {
            String message = "调用接口【/api/v1/refGroupAccount/count/{groupId}时，参数groupId不能为空";
            log.warn(message);
            ApiResult<Integer> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        // 根据默认群组id获取群组人数
        //ServiceResult<Integer> result = refGroupAccountService.getCountByGroupId(groupId);
        String groupCount =(String) redisManager.get(RedisStorage.REF_GROUP_ACCOUNT_BY_GROUP_ID_COUNT_PREFIX + groupId);
        ApiResult<Integer> apiResult = new ApiResult<>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(ServiceResult.SELECT_SUCCESS);
        if (StringUtils.isNotEmpty(groupCount)){
            apiResult.setResult(Integer.valueOf(groupCount));
        }else {
            apiResult.setResult(0);
        }
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 更新用户username默认群组groupId的最近联系时间
     * @return 返回更新结果
     */
    @HystrixCommand
    @ApiOperation(value = "更新用户username默认群组groupId的最近联系时间")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "groupId", value = "默认群组账号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "accountId", value = "用户账号id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "username", value = "用户账号", required = true, dataType = "String")
    })
    @RequestMapping(value = "/updateLastContactTime/{groupId}/{accountId}/{username}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> updateLastContactTime(@PathVariable("groupId") String groupId,
                                                                    @PathVariable("accountId") String accountId,
                                                                    @PathVariable("username") String username,
                                                                    HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(groupId) || StringUtils.isEmpty(accountId) || StringUtils.isEmpty(username)) {
            String message = "调用接口【/api/v1/refGroupAccount/updateLastContactTime/{groupId}/{accountId}/{username}时，参数groupId、accountId、username不能为空";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        // 更新用户username默认群组groupId的最近联系时间
        ServiceResult<Boolean> result = refGroupAccountService.updateLastContactTime(groupId, accountId, username);

        ApiResult<Boolean> apiResult = new ApiResult<>();
        apiResult.setSuccess(result.getSuccess());
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(result.getMessage());
        apiResult.setResult(result.getResult());
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }
}